package com.usian.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sun.xml.internal.ws.handler.HandlerException;
import com.usian.article.client.ArticleClient;
import com.usian.common.dtos.PageResult;
import com.usian.common.enums.AppHttpCodeEnum;
import com.usian.common.exception.LeadException;
import com.usian.common.util.BeanHelper;
import com.usian.model.article.dtos.ArticleDto;
import com.usian.model.article.dtos.AuthorDto;
import com.usian.model.media.dtos.WmUserDto;
import com.usian.model.user.dtos.AuthDto;
import com.usian.model.user.dtos.UserAuthDto;
import com.usian.user.entity.ApUser;
import com.usian.user.entity.ApUserAuth;
import com.usian.user.mapper.ApUserAuthMapper;
import com.usian.user.service.IApUserAuthService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.user.service.IApUserService;
import com.usian.wemedia.client.WemediaFeign;
import io.seata.spring.annotation.GlobalTransactional;
import javafx.fxml.LoadException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.validation.constraints.NotNull;
import java.util.List;

/**
 * <p>
 * APP实名认证信息表 服务实现类
 * </p>
 *
 * @author usian
 * @since 2022-07-05
 */
@Service
public class ApUserAuthServiceImpl extends ServiceImpl<ApUserAuthMapper, ApUserAuth> implements IApUserAuthService {

    @Override
    public PageResult<UserAuthDto> findByPage(AuthDto authDto) {
        //构建分页查询
        Page<ApUserAuth> page = new Page(authDto.getPage(),authDto.getSize());
        //构建查询条件 基于状态eq查询
        Integer status = authDto.getStatus();
        //如果状态不为空的话
        LambdaQueryWrapper<ApUserAuth> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (!StringUtils.isEmpty(status)){
            lambdaQueryWrapper.eq(ApUserAuth::getStatus,status);
        }
        //执行查询
        IPage<ApUserAuth> result = page(page,lambdaQueryWrapper);
        List<ApUserAuth> records = result.getRecords();
        //如果集合中没有的话
        if (CollectionUtils.isEmpty(records)){
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST,"没有该条件的数据");
        }
        List<UserAuthDto> authDtoList = BeanHelper.copyWithCollection(records, UserAuthDto.class);
        return new PageResult<UserAuthDto>(authDto.getPage(),authDto.getSize(),result.getTotal(),authDtoList);
    }

    /**
     * 审核状态
     * 9为通过审核 2为审核失败
     * @param authDto
     * @param status
     */
    @Autowired
    private IApUserService userService;
    @Autowired
    private WemediaFeign wemediaFeign;
    @Autowired
    private ArticleClient articleClient;
    @Override
    @GlobalTransactional //开启全局事务
    public void updateAuthStatus(AuthDto authDto, int status) {
        //对authdto进行判断不能为空
        if (StringUtils.isEmpty(authDto)){
            throw new LeadException(AppHttpCodeEnum.PARAM_INVALID,"参数不正确");
        }
        //参数校验 status只接受是 9 和 2 的
        if (status!=ApUserAuth.Status.FAIL.getCode()&&status!=ApUserAuth.Status.PASS.getCode()){
            //如果不是9和2 返回参数异常
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR,"参数不正确,只接收9或者2");
        }
        //如果是9或者2的话获取id
        Integer authid = authDto.getId();
        //修改用户的状态
        ApUserAuth apUserAuth = new ApUserAuth();
        apUserAuth.setId(authid);
        apUserAuth.setStatus(status);
        apUserAuth.setReason(authDto.getMsg());
        boolean b = updateById(apUserAuth);
        if (!b){
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR,"修改用户状态失败");
        }
        //如果修改成功判断starts是9还是2
        if (status==ApUserAuth.Status.FAIL.getCode()){
            //如果是2之间返回 前面已经修改过状态了所有里面不用修改状态
            return;
        }
        //如果是9的话就创建自媒体用户
        //通过authid查询用户信息
        //自媒体的信息 是用户表中的信息
        //apuserauth 是用户认证的信息 通过认证信息管理用户表去查询用户
        apUserAuth = getById(authid);
        Integer userId = apUserAuth.getUserId();
        //返回一个用户
        ApUser apUser = userService.getById(userId);
        //新建自媒体端
        WmUserDto wmUserDto = new WmUserDto();
        wmUserDto.setPhone(apUser.getPhone());
        wmUserDto.setName(apUser.getName());
        wmUserDto.setImage(apUser.getImage());
        wmUserDto.setPassword(apUser.getPassword());
        wmUserDto.setApUserId(userId);

        wmUserDto.setStatus(status);
        //调用添加方法
        try {
            Integer wmUserId = wemediaFeign.save(wmUserDto);
            //作者表需要关联自媒体表
            wmUserDto.setId(wmUserId);
        } catch (Exception e) {
            e.printStackTrace();
            //失败返回失败信息
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR,"自媒体端创建失败");
        }
        //创建成功封装作者端
        AuthorDto authorDto = new AuthorDto();
        authorDto.setUserId(userId);
        authorDto.setName(apUser.getName());//设置名字
        authorDto.setType(2); //2设置为自媒体人
        authorDto.setWmUserId(wmUserDto.getId());//关联自媒体端口
        try {
            articleClient.saveAuthor(authorDto);
        } catch (Exception e) {
            e.printStackTrace();
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR,"作者创建失败");
        }
        //更新用户的类型
        ApUser user = new ApUser();;
        user.setId(userId);
        user.setFlag(1);
        boolean b1 = userService.updateById(user);
        //测试分布式事务
        //int i=1/0;
        if (!b1){
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR,"修改用户类型失败");
        }

    }
}
